using Spine;
using Spine.Unity;
using UnityEngine;

namespace BehaviorDesigner.Runtime.Tasks.nGame
{
    [TaskCategory("SpineAnimation")]
    [TaskDescription("Returns Success if the animation is currently playing.")]
    public class IsPlaying : Conditional
    {
        [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
        public SharedGameObject targetGameObject;
        [Tooltip("The name of the animation")]
        public SharedString animationName;

        // cache the animation component
        private SkeletonAnimation animation;
        private GameObject prevGameObject;
        private TrackEntry curTrackEntry;

        public override void OnStart()
        {
            var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
            if (currentGameObject != prevGameObject) {
                animation = currentGameObject.GetComponent<SkeletonAnimation>();
                curTrackEntry = animation.state.GetCurrent(1);
                prevGameObject = currentGameObject;
            }
        }

        public override TaskStatus OnUpdate()
        {
            if (animation == null) {
                Debug.LogWarning("Animation is null");
                return TaskStatus.Failure;
            }

            if (curTrackEntry == null)
                return TaskStatus.Success;

            if (curTrackEntry.IsComplete)
                return TaskStatus.Success;

            return TaskStatus.Failure;
        }

        public override void OnReset()
        {
            curTrackEntry = null;
            targetGameObject = null;
            animationName.Value = "";
        }
    }
}